package com.qianfeng.myymatou;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.qianfeng.myymatou.fragment.SaleFragment;
import com.qianfeng.myymatou.fragment.SocialFragment;
import com.qianfeng.myymatou.fragment.LiveFragment;
import com.qianfeng.myymatou.fragment.MineFragment;
import com.qianfeng.myymatou.fragment.HomeFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * 主界面，包含底部选项卡、5个Fragment页面
 */
public class MainActivity extends AppCompatActivity {

    @InjectView(R.id.fl_frag_container) FrameLayout mFlFragContainer;
    @InjectView(R.id.rg_tabs) RadioGroup mRgTabs;

    private List<Fragment> mFragsList;
    private int mPreviousIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);

        //初始化五个主界面Fragment
        initFragList();

        //设置底部RadioGroup的监听
        mRgTabs.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
        //设置默认显示首页
        ((RadioButton) mRgTabs.getChildAt(mPreviousIndex)).setChecked(true);

    }

    /**
     * 对底部的切换按钮做监听
     */
    private class MyOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener{
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton currentRb= (RadioButton) group.findViewById(checkedId);
            int currentIndex=group.indexOfChild(currentRb);
            convertFrag(currentIndex, mPreviousIndex);
            mPreviousIndex =currentIndex;
        }
    }

    /**
     * 对Fragment的显示和隐藏逻辑
     * @param showIndex 要显示的Fragment的下标
     * @param hideIndex 要隐藏的Fragment的下标
     */
    private void convertFrag(int showIndex, int hideIndex) {
        Fragment showFrag=mFragsList.get(showIndex);
        Fragment hideFrag=mFragsList.get(hideIndex);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (!showFrag.isAdded()){
            ft.add(R.id.fl_frag_container,showFrag);
        }
        if (showIndex==hideIndex){
            ft.show(showFrag).commit();
        }else {
            ft.show(showFrag).hide(hideFrag).commit();
        }
    }

    private void initFragList(){
        mFragsList=new ArrayList<>();
        mFragsList.add(new HomeFragment());//主页
        mFragsList.add(new LiveFragment());//直播
        mFragsList.add(new SaleFragment());//特卖
        mFragsList.add(new SocialFragment());//社区
        mFragsList.add(new MineFragment());//我的
    }
}
